<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        <el-form-item label="">
          <el-input v-model="searchInfo.DID" placeholder="请输入DID" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button icon="refresh" @click="onFresh">刷新</el-button>
        <ExportExcel template-id="" :limit="9999" />
        <ImportExcel template-id="" @on-success="getTableData" />
      </div>
      <el-table :data="sortedTableData" @selection-change="handleSelectionChange" @sort-change="sortChange">
        <el-table-column align="left" label="序号" min-width="60" type="index"/>
        <el-table-column align="left" label="用户名" min-width="150" prop="userName" sortable="custom" />
        <el-table-column align="left" label="DID" min-width="180" prop="DID" sortable="custom" />
        <el-table-column align="left" label="身份证号" min-width="180" prop="idCard" />
        <el-table-column align="left" label="电话号" min-width="150" prop="phone" />
        <el-table-column align="left" label="银行卡号" min-width="150" prop="bankCard" />
        <el-table-column align="left" label="审核进度" min-width="150" prop="auditProgress" sortable="custom" />
        <el-table-column align="left" label="审核状态" min-width="150" prop="auditStatus" sortable="custom">
          <template #default="scope">
            <span>{{ formatStatus(scope.row.auditStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button icon="edit" type="primary" link @click="openDrawer('查看详情', scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 查看详情抽屉 -->
    <el-drawer v-model="drawerVisible" size="60%" :before-close="closeDrawer" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ drawerTitle }}</span>
          <div>
            <el-button @click="closeDrawer">取消</el-button>
            <el-button @click="submitForm">确定</el-button>
          </div>
        </div>
      </template>
      <el-form ref="userForm" :model="userInfo" label-width="100px">
        <el-form-item label="DID">
          <el-input v-model="userInfo.DID" disabled />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="userInfo.userName" disabled />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="userInfo.idCard" disabled />
        </el-form-item>
        <el-form-item label="电话号">
          <el-input v-model="userInfo.phone" disabled />
        </el-form-item>
        <el-form-item label="银行卡号">
          <el-input v-model="userInfo.bankCard" disabled />
        </el-form-item>
        <el-form-item label="审核进度">
          <el-input v-model="userInfo.auditProgress" disabled />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="userInfo.auditStatus" placeholder="请选择审核状态">
            <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ExportExcel from '@/components/exportExcel/exportExcel.vue'
import { getApplyNWYLUser, getapplyNWYLUserDetail,handleApply } from '@/api/userControl'

// 原始数据
const originalTableData = ref([])

// 审核状态选项
const statusOptions = ref([
  { label: '未完成', value: 0 },
  { label: '完成', value: 1 },
])

// 分页相关数据
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)

// 表格数据
const tableData = ref([])

// 搜索信息
const searchInfo = reactive({ DID: '' })

// 选中的用户
const selectedUsers = ref([])

// 抽屉的显示状态及标题
const drawerVisible = ref(false)
const drawerTitle = ref('')

// 用户信息
const userInfo = reactive({
  DID: '',
  userName: '',
  idCard: '',
  phone: '',
  bankCard: '',
  auditProgress: '',
  auditStatus: ''
})

const formatStatus = (status) => {
  const statusOption = statusOptions.value.find(option => option.value === status)
  return statusOption ? statusOption.label : ''
}

// 排序信息
const sortInfo = ref({ prop: '', order: '' })

// 获取排序后的数据
const sortedTableData = computed(() => {
  const data = [...tableData.value]
  if (sortInfo.value.prop && sortInfo.value.order) {
    data.sort((a, b) => {
      const aValue = a[sortInfo.value.prop]
      const bValue = b[sortInfo.value.prop]

      if (typeof aValue === 'string') {
        return sortInfo.value.order === 'ascending'
            ? aValue.localeCompare(bValue)
            : bValue.localeCompare(aValue)
      } else if (typeof aValue === 'number') {
        return sortInfo.value.order === 'ascending'
            ? aValue - bValue
            : bValue - aValue
      } else {
        return 0
      }
    })
  }
  return data
})

// 搜索按钮点击事件
const onSubmit = async () => {
  try {
    await getTableData();
  } catch (error) {
    console.error('Search error:', error);
  }
}

// 重置按钮点击事件
const onReset = () => {
  searchInfo.DID = ''
  tableData.value = [...originalTableData.value]
  total.value = originalTableData.value.length
  page.value = 1 // 重置分页到第1页
}

// 打开抽屉
const loading = ref(false);

const openDrawer = async (title, row) => {
  drawerTitle.value = title === '新增' ? '新增用户' : '查看详情';
  loading.value = true; // 开始加载

  try {
    const response = await getapplyNWYLUserDetail(row.DID); // 调用获取详情的接口
    const userDetail = response.data;
    userInfo.DID = userDetail.DID;
    userInfo.userName = userDetail.UserName;
    userInfo.idCard = userDetail.IdCard;
    userInfo.phone = userDetail.UserPhone;
    userInfo.bankCard = userDetail.BankCadId;
    userInfo.auditProgress = userDetail.ApplyProcess;
    userInfo.auditStatus = userDetail.ApplyStatus;

    drawerVisible.value = true;
  } catch (error) {
    console.error('获取用户详情失败:', error);
    ElMessage.error('获取用户详情失败');
  } finally {
    loading.value = false; // 加载完成
  }
};

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false
}

// 提交表单
const submitForm = async () => {
  try {
    const applyResult = userInfo.auditStatus; // 获取审核状态
    const did = userInfo.DID; // 获取用户 DID

    // 调用 API 函数，并传入正确的参数格式
    const response = await handleApply({
      ApplyResult: applyResult,
      Did: did
    });
    if (response.code === 0) {
      ElMessage.success('操作成功');


      closeDrawer();
      await getTableData(); // 确保数据刷新完成
    } else {
      ElMessage.error('操作失败');
    }
  } catch (error) {
    console.error('API 请求错误:', error);
    ElMessage.error('请求失败');
  }
};



// 删除按钮点击事件
const onDelete = () => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage({ type: 'success', message: '删除成功' })
    // 删除按钮逻辑
  }).catch(() => {
    console.log('取消删除')
  })
}

// 刷新按钮点击事件
const onFresh = () => {
  ElMessageBox.confirm('确定要刷新吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage({ type: 'success', message: '刷新成功' })
    getTableData()
  }).catch(() => {
    console.log('取消刷新')
  })
}

// 选择变化处理
const handleSelectionChange = (val) => {
  selectedUsers.value = val
}

// 处理排序变化
const sortChange = ({ prop, order }) => {
  sortInfo.value = { prop, order }
}

// 获取表格数据
const getTableData = async () => {
  try {
    const response = await getApplyNWYLUser(page.value, pageSize.value);
    tableData.value = response.data.AuditList.map(item => ({
      DID: item.DID,
      userName: item.UserName,
      idCard: item.IdCard,
      phone: item.UserPhone,
      bankCard: item.BankCadId,
      auditProgress: item.ApplyProcess,
      auditStatus: item.ApplyStatus
    })) || [];
    originalTableData.value = tableData.value;
    total.value = response.data.totalNum;
  } catch (error) {
    console.error('API Error:', error);
    ElMessage.error('获取数据失败');
  }
}

// 处理分页改变
const handleCurrentChange = (currentPage) => {
  page.value = currentPage
  getTableData()
}

// 处理每页条数改变
const handleSizeChange = (size) => {
  pageSize.value = size
  getTableData()
}

getTableData()


</script>

<style scoped lang="scss">
.warning {
  color: #dc143c;
}
</style>
